package com.imc.platform.base.user.security;

import com.imc.platform.base.menu.dao.repository.MenuRepository;
import com.imc.platform.base.user.dao.repository.UserRepository;
import com.imc.platform.base.menu.pojo.Menu;
import com.imc.platform.base.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by tanweiping on 2018/7/20.
 */
/*
* 类描述：自定义UserDetailsService 接口实现
* 开发者：tanweiping
* 创建日期：2018/8/7 10:33
*/
@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;
    @Autowired
    MenuRepository menuRepository;

    /*
    * tanweiping  2018/8/7 10:33
    * 方法描述：加载用户信息
    */
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findAllByLoginName(username);
        if (user != null) {
            Set<Menu> permissions = menuRepository.findAllByUserId(String.valueOf(user.getId()));
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            for (Menu permission : permissions) {
                if (permission != null && permission.getMenuName()!=null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getMenuName());
                    //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                        grantedAuthorities.add(grantedAuthority);
                }
            }
            return new org.springframework.security.core.userdetails.User(user.getLoginName(), user.getLoginPwd(), grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("admin: " + username + " do not exist!");
        }
    }

}